package com.example.admin.controller;
import com.example.admin.service.CategoryService;
import com.example.xo.common.Result;
import com.example.xo.pojo.Category;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 王同学
 */
@RestController
@RequestMapping("category")
@Slf4j
public class CategoryController {
    @Autowired
    private CategoryService categoryService;
    @PostMapping("add")
    public Result add(@RequestBody Category category){
        //如果名字的长度大于20那么就给他结束掉
        if (category.getCategoryName().length()>20){
            log.info("{}超过20个字符",category.getCategoryName());
            //超过就失败
                return Result.error();
        }
        //成功
        return Result.success(categoryService.add(category));
    }
    @GetMapping("findAll")
    public Result findAll(){
        List<Category> list = categoryService.findAll();
        return Result.success(list);
    }
    @GetMapping("{id}")
    public Result findById(@PathVariable String id){
        Category byId = categoryService.findById(id);
        return Result.success(byId);

    }

    @PutMapping("update")
    public Result update(@RequestBody Category category){
        if (category.getCategoryName().length()>20){
            log.info("名字长度超过20{}",category.getCategoryName());
            return Result.error();
        }
        boolean res = categoryService.update(category);
        return Result.success(res);
    }

    @DeleteMapping("{id}")
    public Result deleteById(@PathVariable String id){
        log.info("删除了一个:{}",id);
        boolean rss = categoryService.deleteById(id);

        return Result.success(rss);
    }
}
